import {
	useCookie
} from '#app'

export const useToken = () => {
	const cookieOptions = {
		path: '/',
		sameSite: 'lax',
		secure: process.env.NODE_ENV === 'production'
	}

	// 统一创建 cookie 对象
	const token = useCookie('token', cookieOptions)

	// ✅ 获取 token，优先从 cookie，客户端刷新时 fallback 到 localStorage
	const getToken = () => {
		if (process.client) {
			return token.value || localStorage.getItem('token')
		}
		return token.value
	}

	// ✅ 设置 token，同时写入 cookie 和 localStorage
	const setToken = (tokenValue) => {
		token.value = tokenValue
		if (process.client && tokenValue) {
			localStorage.setItem('token', tokenValue)
			document.cookie = `token=${tokenValue}; Path=/;`
		}
	}

	// ✅ 清除 token
	const clearToken = () => {
		token.value = null
		if (process.client) {
			localStorage.removeItem('token')
			document.cookie = `token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;`
		}
	}

	return {
		getToken,
		setToken,
		clearToken
	}
}